package cn.wolfcode.rbac.web.controller;

import cn.wolfcode.rbac.domain.Employee;
import cn.wolfcode.rbac.qo.JSONResult;
import cn.wolfcode.rbac.service.IEmployeeService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
public class UserController {
    @Autowired
    private IEmployeeService employeeService;


    @RequestMapping("/userLogin")
    @ResponseBody
    public JSONResult login(String username, String password, HttpServletRequest request){
//        JSONResult jsonResult=new JSONResult();
//        Employee employee = employeeService.selectByName(username, password);
//
//        if(employee != null)
//        {
//            jsonResult.setSuccess(true);
//            jsonResult.setMsg("登录成功");
//            HttpSession session = request.getSession();
//            session.setAttribute("EXPRESSION_IN_SESSION",employeeService.selectPermissonByEmployeeId(employee.getId()));
//            session.setAttribute("USER_IN_SESSION", employee);
//        }
//        else {
//            jsonResult.setSuccess(false);
//            jsonResult.setMsg("登录失败");
//        }
//        return jsonResult;
        try {
            UsernamePasswordToken token=new UsernamePasswordToken(username,password);
            Subject subject= SecurityUtils.getSubject();
            subject.login(token);
            System.out.println("验证为"+subject.isAuthenticated());
            subject.getSession().setAttribute("name",username);
            //subject.getSession().setAttribute("USER_IN_SESSION",subject.getPrincipal());
            return new JSONResult(true,"登录成功");
        }catch(UnknownAccountException e){
            return new JSONResult(false,"账号不存在");
        }catch (IncorrectCredentialsException e){
            return new JSONResult(false,"账号密码有误");
        }catch (Exception e){
            e.printStackTrace();
            return new JSONResult(false,"登录异常,请联系管理员");
        }


    }

    @RequestMapping("/logout")
    @ResponseBody
    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        Subject subject= SecurityUtils.getSubject();
//        subject.logout();
//        //subject.getSession().removeAttribute("USER_IN_SESSION");
//        subject.getSession().removeAttribute("name");
//        response.sendRedirect("/login.html");
    }
}
